﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Common.Logging;
using WuDada.Core.Post;
using WuDada.Core.Post.Domain;
using WuDada.Core.Post.Service;
using WuDada.Core.SystemApplications.Domain;
using WuDada.Core.Auth.Domain;
using WuDada.Provider.ResourceHandle.Service;
using WuDada.Provider.ResourceHandle;
using WuDada.Provider.ResourceHandle.Domain;
using System.IO;

public partial class admin_UC03_0301_1 : System.Web.UI.Page
{
    private ILog m_Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    private PostFactory m_PostFactory;
    private IPostService m_PostService;
    private StorageFactory m_StorageFactory;
    private IStorageFileService m_StorageFileService;
    private WebLogService m_WebLogService;

    //傳入的父層Id
    public int parentPostId
    {
        get { if (ViewState["parent"] == null) { ViewState["parent"] = 0; } return int.Parse(ViewState["parent"].ToString()); }
        set { ViewState["parent"] = value; }
    }
    private string m_ParentPath = "0301.aspx";

    private int m_Mode
    {
        get { if (ViewState["mode"] == null) { ViewState["mode"] = 0; } return int.Parse(ViewState["mode"].ToString()); }
        set { ViewState["mode"] = value; }
    }
    private string m_PicFileName
    {
        get { if (ViewState["picfilename"] == null) { ViewState["picfilename"] = string.Empty; } return ViewState["picfilename"].ToString(); }
        set { ViewState["picfilename"] = value; }
    }

    private StorageFileVO m_StorageFile
    {
        get { if (ViewState["storageFile"] == null) { ViewState["storageFile"] = new StorageFileVO(); } return (StorageFileVO)ViewState["storageFile"]; }
        set { ViewState["storageFile"] = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        m_WebLogService = new WebLogService();
        m_PostFactory = new PostFactory();
        m_PostService = m_PostFactory.GetPostService();
        m_StorageFactory = new StorageFactory();
        m_StorageFileService = m_StorageFactory.GetStorageFileService();

        if (!IsPostBack)
        {
            pnlContent.Visible = false;
            parentPostId = QueryStringHelper.GetInteger("parent", 0);
            PostVO parentPost = m_PostService.GetPostById(parentPostId);
            if (parentPost == null)
            {
                string strJs = JavascriptUtil.AlertJSAndRedirect("查無父層分類資訊", m_ParentPath);
                ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "js", strJs, false);
            }

            lblParentTitle.Text = parentPost.Title;
            fillGridView();
            ShowMode();
        }
    }

    private void ShowMode()
    {
        if (m_Mode == 0)
        {
            btnAdd.Visible = true;
            btnSave.Visible = false;
        }
        else
        {
            btnAdd.Visible = false;
            btnSave.Visible = true;
        }
    }

    private void fillGridView()
    {
        //搜尋條件
        string sortField = "SortNo";
        bool sortDesc = false;

        //分頁
        AspNetPager1.RecordCount = m_StorageFileService.CountStorageFileListBySourceId(
            StorageFileVO.StorageSourceType.Post, parentPostId);
        int pageIndex = (AspNetPager1.CurrentPageIndex - 1);
        int pageSize = AspNetPager1.PageSize;

        gvList.DataSource = m_StorageFileService.GetStorageFileListBySourceId(
            StorageFileVO.StorageSourceType.Post, parentPostId, pageIndex, pageSize, sortField, sortDesc);
        gvList.DataBind();
    }

    protected void AspNetPager1_PageChanged(object sender, EventArgs e)
    {
        fillGridView();
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        try
        {
            StorageFileVO storageFileVO = m_StorageFile;
            storageFileVO.SourceId = parentPostId;
            storageFileVO.SourceType = StorageFileVO.StorageSourceType.Post;
            //storageFileVO.FileName = m_PicFileName;
            storageFileVO.DisplayName = txtTitle.Text.Trim();
            storageFileVO.SortNo = int.Parse(txtSortNo.Text.Trim());
            m_StorageFileService.UpdateStorageFile(storageFileVO);
            //m_WebLogService.FillAdminOprtAction(storageFileVO, FuncOprt.OprtAction.INSERT);
            m_WebLogService.AddSystemLog(MsgVO.Action.新增, storageFileVO);
            ClearUI();
            fillGridView();
        }
        catch (Exception ex)
        {
            m_Log.Error(ex);
            lblMsg.Text = "新增失敗，請確認圖片是否上傳";
        }
    }

    private void ClearUI()
    {
        m_Mode = 0;
        m_StorageFile = null;
        ltlImg.Text = string.Empty;
        txtTitle.Text = string.Empty;
        txtSortNo.Text = string.Empty;
        pnlContent.Visible = false;
        btnShowAdd.Enabled = true;
    }

    private string GetPic()
    {
        return string.Format("<img src='../../common/storagefilepichandler.ashx?fileid={0}' width='145' height='108' border='0' />"
            , m_StorageFile.StorageFileId);
    }

    protected void gvList_RowCommand1(object sender, GridViewCommandEventArgs e)
    {
        string cmdName = e.CommandName;
        int fileId = int.Parse(e.CommandArgument.ToString());
        StorageFileVO storageFileVO = m_StorageFileService.GetStorageFileById(fileId);
        switch (cmdName)
        {
            case "myModify":
                ClearUI();
                m_StorageFile = storageFileVO;
                m_Mode = fileId;
                ltlImg.Text = GetPic();
                txtTitle.Text = storageFileVO.DisplayName;
                txtSortNo.Text = storageFileVO.SortNo.ToString();
                ShowMode();
                pnlContent.Visible = true;
                break;
            case "myDel":
                m_StorageFileService.DeleteStorageFile(storageFileVO);
                m_WebLogService.AddSystemLog(MsgVO.Action.刪除, storageFileVO);
                break;
            default:
                break;
        }
        fillGridView();
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        ClearUI();
        ShowMode();
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            StorageFileVO storageFileVO = m_StorageFile;
            storageFileVO.SourceId = parentPostId;
            storageFileVO.SourceType = StorageFileVO.StorageSourceType.Post;
            storageFileVO.DisplayName = txtTitle.Text.Trim();
            storageFileVO.SortNo = int.Parse(txtSortNo.Text.Trim());
            m_StorageFileService.UpdateStorageFile(storageFileVO);
            //m_WebLogService.FillAdminOprtAction(storageFileVO, FuncOprt.OprtAction.INSERT);
            m_WebLogService.AddSystemLog(MsgVO.Action.修改, storageFileVO);
            fillGridView();
            ClearUI();
            ShowMode();
        }
        catch (Exception ex)
        {
            m_Log.Error(ex);
            lblMsg.Text = "更新失敗，請確認圖片是否上傳";
        }
    }

    protected void gvList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex != -1)
        {
            Control ctrl = e.Row;
            StorageFileVO storageFileVO = (StorageFileVO)e.Row.DataItem;
            int storageFileId = int.Parse(UIHelper.FindHiddenValue(ref ctrl, "hdnStorageFileId"));
            string pic = string.Format(@"<a title='{1}' rel='lightbox[pics]' href='../../common/storagefilepichandler.ashx?fileid={0}'>
                <img src='../../common/storagefilepichandler.ashx?fileid={0}' width='60' border='0' />"
            , storageFileId, storageFileVO.DisplayName);
            UIHelper.SetLiteralText(ctrl, "ltlPic", pic);
        }
    }

    protected void btnShowAdd_Click(object sender, EventArgs e)
    {
        ClearUI();
        m_PicFileName = string.Empty;
        ShowMode();
        pnlContent.Visible = true;
        btnShowAdd.Enabled = false;
    }

    protected void ddlSelect_SelectedIndexChanged(object sender, EventArgs e)
    {
        fillGridView();
    }

    protected void btnUpliad_Click(object sender, EventArgs e)
    {
        try
        {
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];
                if (hpf.ContentLength > 0)
                {
                    DirectoryInfo dir = m_StorageFileService.GetStorageDirectory(FolderType.UPLOAD_FOLDER, true);
                    string sourceFileName = System.IO.Path.GetFileName(hpf.FileName);
                    string sourceFilePath = Path.Combine(dir.FullName, sourceFileName);
                    hpf.SaveAs(sourceFilePath);
                    FileInfo sourceFileInfo = new FileInfo(sourceFilePath);
                    string newFileName = Guid.NewGuid().ToString() + sourceFileInfo.Extension;
                    string destFileName = Path.Combine(dir.FullName, newFileName);
                    File.Copy(sourceFilePath, destFileName);

                    StorageFileVO storageFileVO = m_StorageFile;
                    storageFileVO.SourceUri = sourceFileInfo.FullName;
                    storageFileVO.CurrentPath = destFileName;
                    storageFileVO.FileName = sourceFileInfo.Name;
                    storageFileVO.DisplayName = sourceFileInfo.Name;
                    storageFileVO.FileSize = sourceFileInfo.Length;
                    if (storageFileVO.StorageFileId == 0)
                    {
                        storageFileVO = m_StorageFileService.CreateStorageFile(storageFileVO);
                    }
                    else
                    {
                        storageFileVO = m_StorageFileService.UpdateStorageFile(storageFileVO);
                    }

                    m_StorageFile = storageFileVO;
                    ltlImg.Text = GetPic();
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "js", JavascriptUtil.AlertJS("請點選您要上傳的照片!"), false);
                    return;
                }
            }
        }
        catch(Exception ex)
        {
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "js", JavascriptUtil.AlertJS("檔案傳輸錯誤!" + ex.ToString()), false);
            return;
        }
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect(m_ParentPath);
    }
}